package org.dawfinn.droiditarian.deedlocationsource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.dawfinn.droiditarian.data.DeedLocation;
import org.dawfinn.droiditarian.proto.Droiditarian;

public class InternetDeedLocationSource implements DeedLocationSource {

	private final String path;

	public InternetDeedLocationSource(String path) {
		this.path = path;
	}

	public List<DeedLocation> getDeedLocations() throws IOException {
		return parseDeedLocations(new URL(path).openStream());
	}

	private List<DeedLocation> parseDeedLocations(InputStream in) throws IOException {
		List<DeedLocation> deedLocs = new ArrayList<DeedLocation>();
		Droiditarian.DeedLocation proto;

		while ((proto = Droiditarian.DeedLocation.parseDelimitedFrom(in)) != null) {
			deedLocs.add(new DeedLocation(proto.getLat(), proto.getLng(), proto.getDeedTitle(), proto.hasPicture() ? proto.getPicture() : null, proto
			        .hasLocality() ? proto.getLocality() : null, proto.hasCountry() ? proto.getCountry() : null, proto.hasKey() ? proto.getKey()
			        : null));
		}

		return deedLocs;
	}

}
